﻿using System;
using System.Collections.Generic;
using CoreCms.Net.Configuration;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Utility.Extensions;
using CoreCms.Net.Utility.Helper;
using SqlSugar;
using CoreCms.Net.Caching.AccressToken;
using CoreCms.Net.DTO.WeChatShipping;
using CoreCms.Net.IServices;
using CoreCms.Net.WeChat.Service.HttpClients;
using CoreCms.Net.WeChat.Service.Enums;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using SKIT.FlurlHttpClient.Wechat.Api;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Web.Admin.Infrastructure;

namespace CoreCms.Net.Web.Admin.Controllers.WeChatShipping
{

    /// <summary>
    /// 微信发货信息订单管理
    ///</summary>
    [Description("微信发货信息订单管理")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    [RequiredErrorForAdmin]
    [Authorize(Permissions.Name)]
    public class WeChatShippingOrderController : ControllerBase
    {

        private readonly IWeChatApiHttpClientFactory _weChatApiHttpClientFactory;
        private readonly ICoreCmsBillPaymentsServices _billPaymentsServices;
        private readonly ICoreCmsOrderServices _orderServices;
        private readonly ICoreCmsOrderItemServices _orderItemServices;
        private readonly ICoreCmsServicesServices _servicesServices;
        private readonly IWeChatShippingDeliveryServices _weChatShippingDeliveryServices;
        private readonly ICoreCmsBillDeliveryServices _billDeliveryServices;


        /// <summary>
        /// 构造函数
        /// </summary>
        public WeChatShippingOrderController(IWeChatApiHttpClientFactory weChatApiHttpClientFactory, ICoreCmsBillPaymentsServices billPaymentsServices, ICoreCmsOrderServices orderServices, ICoreCmsOrderItemServices orderItemServices, ICoreCmsServicesServices servicesServices, IWeChatShippingDeliveryServices weChatShippingDeliveryServices, ICoreCmsBillDeliveryServices billDeliveryServices)
        {
            _weChatApiHttpClientFactory = weChatApiHttpClientFactory;
            _billPaymentsServices = billPaymentsServices;
            _orderServices = orderServices;
            _orderItemServices = orderItemServices;
            _servicesServices = servicesServices;
            _weChatShippingDeliveryServices = weChatShippingDeliveryServices;
            _billDeliveryServices = billDeliveryServices;
        }


        #region 获取列表============================================================

        // POST: Api/CoreCmsBillReship/GetPageList
        /// <summary>
        ///     获取列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("获取列表")]
        public async Task<AdminUiCallBack> GetPageList()
        {
            var jm = new AdminUiCallBack();
            var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
            var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(20);

            var last_index = Request.Form["last_index"].FirstOrDefault();

            //获取排序字段

            //设置排序方式
            var orderDirection = Request.Form["orderDirection"].FirstOrDefault();
            var orderBy = orderDirection switch
            {
                "asc" => OrderByType.Asc,
                "desc" => OrderByType.Desc,
                _ => OrderByType.Desc
            };
            //查询筛选


            //构建请求
            var client = _weChatApiHttpClientFactory.CreateWxOpenClient();
            var accessToken = WeChatCacheAccessTokenHelper.GetWxOpenAccessToken();
            var request = new WxaSecOrderGetOrderListRequest()
            {
                AccessToken = accessToken
            };

            //构建查询
            var status = Request.Form["status"].FirstOrDefault().ObjectToInt(0);
            if (status > 0)
            {
                request.OrderState = status;
            }

            if (pageCurrent > 1)
            {
                request.Limit = pageCurrent;
            }

            if (!string.IsNullOrEmpty(last_index))
            {
                request.Offset = last_index;
            }

            if (pageSize > 0)
            {
                request.Limit = pageSize;
            }

            var response = await client.ExecuteWxaSecOrderGetOrderListAsync(request, HttpContext.RequestAborted);
            if (response.ErrorCode == (int)WeChatReturnCode.ReturnCode.请求成功)
            {

                //返回数据
                jm.data = response.OrderList;
                jm.otherData = response;
                jm.code = 0;
                jm.count = 10000;
                jm.msg = "数据调用成功!";
            }
            else
            {
                jm.code = 1;
                jm.msg = response.ErrorMessage;
            }

            //获取数据

            return jm;
        }

        #endregion

        #region 首页数据============================================================

        // POST: Api/CoreCmsBillReship/GetIndex
        /// <summary>
        ///     首页数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("首页数据")]
        public AdminUiCallBack GetIndex()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };

            var status = EnumHelper.EnumToList<GlobalEnumVars.WeChatShippingOrderStatus>();
            var logisticsType = EnumHelper.EnumToList<GlobalEnumVars.WeChatShippingLogisticsType>();

            jm.data = new
            {
                status,
                logisticsType
            };


            return jm;
        }

        #endregion

        #region 创建发货单============================================================
        /// <summary>
        /// 创建发货单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("创建数据")]
        public async Task<AdminUiCallBack> GetCreate([FromBody] FMStringId entity)
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };

            var paymentOrder = await _billPaymentsServices.QueryByClauseAsync(p => p.paymentId == entity.id);
            if (paymentOrder == null)
            {
                jm.msg = "支付单获取失败";
                return jm;
            }

            var billDeliveryList = new List<CoreCmsBillDelivery>();

            var orderTitle = string.Empty;
            var logisticsTypeValue = 0;
            if (paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.Recharge)
            {
                orderTitle = "用户充值" + paymentOrder.money + "元";
                logisticsTypeValue = (int)GlobalEnumVars.WeChatShippingLogisticsType.虚拟商品;
            }
            else if (paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.FormOrder)
            {
                orderTitle = "表单订单";
                logisticsTypeValue = (int)GlobalEnumVars.WeChatShippingLogisticsType.虚拟商品;
            }
            else if (paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.FormPay)
            {
                orderTitle = "表单付款码支付";
                logisticsTypeValue = (int)GlobalEnumVars.WeChatShippingLogisticsType.虚拟商品;
            }
            else if (paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.ServiceOrder)
            {
                var id = Convert.ToInt32(paymentOrder.sourceId);
                var serviceModel = await _servicesServices.QueryByClauseAsync(p => p.id == id);
                if (serviceModel == null)
                {
                    jm.msg = "服务项目获取失败";
                    return jm;
                }

                orderTitle = serviceModel.title;
                logisticsTypeValue = (int)GlobalEnumVars.WeChatShippingLogisticsType.虚拟商品;
            }
            else if (paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.Common
                        || paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.PinTuan
                        || paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.Group
                        || paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.Seckill
                        || paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.Solitaire
                     )
            {

                billDeliveryList = await _billDeliveryServices.QueryListByClauseAsync(p => p.orderId == paymentOrder.sourceId);
                //获取订单
                var order = await _orderServices.QueryByClauseAsync(p => p.orderId == paymentOrder.sourceId);
                if (order == null)
                {
                    jm.msg = "关联订单获取失败";
                    return jm;
                }

                logisticsTypeValue = order.receiptType switch
                {
                    //设置物流的发货模式
                    (int)GlobalEnumVars.OrderReceiptType.SelfDelivery => (int)GlobalEnumVars.WeChatShippingLogisticsType.用户自提,
                    (int)GlobalEnumVars.OrderReceiptType.IntraCityService => (int)GlobalEnumVars.WeChatShippingLogisticsType.同城配送,
                    (int)GlobalEnumVars.OrderReceiptType.Logistics => (int)GlobalEnumVars.WeChatShippingLogisticsType.物流配送,
                    _ => logisticsTypeValue
                };
                var orderItems = await _orderItemServices.QueryListByClauseAsync(p => p.orderId == paymentOrder.sourceId);
                if (!orderItems.Any())
                {
                    jm.msg = "订单详情获取失败";
                    return jm;
                }
                else
                {
                    if (orderItems.Count == 1)
                    {
                        orderTitle = orderItems.FirstOrDefault()?.name;
                    }
                    else
                    {
                        orderItems.ForEach(p => { orderTitle += p.name + ";"; });
                    }
                }

            }
            else if (paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.Bargain)
            {
                orderTitle = "砍价活动";
                logisticsTypeValue = (int)GlobalEnumVars.WeChatShippingLogisticsType.物流配送;
            }
            else if (paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.Giveaway)
            {
                orderTitle = "购物赠品";
                logisticsTypeValue = (int)GlobalEnumVars.WeChatShippingLogisticsType.虚拟商品;
            }
            else
            {
                jm.msg = "订单类型获取失败";
                return jm;
            }

            var status = EnumHelper.EnumToList<GlobalEnumVars.WeChatShippingOrderStatus>();
            var logisticsType = EnumHelper.EnumToList<GlobalEnumVars.WeChatShippingLogisticsType>();


            //构建请求
            var client = _weChatApiHttpClientFactory.CreateWxOpenClient();
            var accessToken = WeChatCacheAccessTokenHelper.GetWxOpenAccessToken();
            var request = new WxaSecOrderGetOrderRequest
            {
                AccessToken = accessToken,
                TransactionId = entity.data.ToString(),
                OutTradeNumber = entity.id
            };

            var deliveryCompany = await _weChatShippingDeliveryServices.GetCaChe();


            var response = await client.ExecuteWxaSecOrderGetOrderAsync(request, HttpContext.RequestAborted);
            if (response.IsSuccessful())
            {
                jm.code = 0;
                jm.data = new
                {
                    response.Order,
                    status,
                    logisticsType,
                    orderTitle,
                    deliveryCompany,
                    billDeliveryList,
                    paymentOrder,
                    logisticsTypeValue
                };
            }
            else
            {
                jm.code = 1;
                jm.msg = response.ErrorMessage;
            }
            return jm;
        }
        #endregion

        #region 创建提交============================================================
        // POST: Api/CoreCmsAgent/DoCreate
        /// <summary>
        /// 创建提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("创建提交")]
        public async Task<AdminUiCallBack> DoCreate([FromBody] OrderShippingCreatePost entity)
        {
            var jm = new AdminUiCallBack();

            var shippingList = new List<WxaSecOrderUploadShippingInfoRequest.Types.Shipping>();

            if (entity.logistics_type == (int)GlobalEnumVars.WeChatShippingLogisticsType.物流配送)
            {
                if (entity.shipping_list == null || !entity.shipping_list.Any())
                {
                    jm.msg = "物流配送请完善快递信息";
                    return jm;
                }

                foreach (var item in entity.shipping_list)
                {
                    if (string.IsNullOrEmpty(item.express_company) && string.IsNullOrEmpty(item.tracking_no))
                    {
                        jm.msg = "请填写完整的快递信息";
                        return jm;
                    }
                    var shipping = new WxaSecOrderUploadShippingInfoRequest.Types.Shipping
                    {
                        ItemDescription = entity.item_desc,
                        ExpressCompany = item.express_company,
                        TrackingNumber = item.tracking_no
                    };
                    shippingList.Add(shipping);
                }
            }
            else if (entity.logistics_type == (int)GlobalEnumVars.WeChatShippingLogisticsType.同城配送)
            {
                var shipping = new WxaSecOrderUploadShippingInfoRequest.Types.Shipping
                {
                    ItemDescription = entity.item_desc,
                    ExpressCompany = entity.cityDistributionName,
                    TrackingNumber = entity.cityDistributionNumber
                };
                shippingList.Add(shipping);
            }
            else if (entity.logistics_type == (int)GlobalEnumVars.WeChatShippingLogisticsType.用户自提 || entity.logistics_type == (int)GlobalEnumVars.WeChatShippingLogisticsType.虚拟商品)
            {
                var shipping = new WxaSecOrderUploadShippingInfoRequest.Types.Shipping
                {
                    ItemDescription = entity.item_desc
                };
                shippingList.Add(shipping);
            }
            else
            {
                jm.msg = "请提交合理的物流模式";
                return jm;
            }

            var request = new WxaSecOrderUploadShippingInfoRequest
            {
                OrderKey = new WxaSecOrderUploadCombinedShippingInfoRequest.Types.OrderKey()
                {
                    OrderNumberType = 2,
                    TransactionId = entity.transaction_id,
                    MerchantId = entity.merchant_id,
                    OutTradeNumber = entity.merchant_trade_no
                },
                LogisticsType = entity.logistics_type,
                IsFinishAll = entity.is_all_delivered,
                ShippingList = shippingList,
                Payer = new WxaSecOrderUploadCombinedShippingInfoRequest.Types.Payer() { OpenId = entity.openid }
            };

            if (request.LogisticsType == (int)GlobalEnumVars.WeChatShippingLogisticsType.物流配送 && request.IsFinishAll == true)
            {
                if (shippingList.Count == 1)
                {
                    request.DeliveryMode = (int)GlobalEnumVars.WeChatShippingDeliveryMode.UNIFIED_DELIVERY;
                }
                else
                {
                    request.DeliveryMode = (int)GlobalEnumVars.WeChatShippingDeliveryMode.SPLIT_DELIVERY;
                }
            }
            else if (request.LogisticsType == (int)GlobalEnumVars.WeChatShippingLogisticsType.物流配送 && request.IsFinishAll == false)
            {
                request.DeliveryMode = (int)GlobalEnumVars.WeChatShippingDeliveryMode.SPLIT_DELIVERY;
            }
            else
            {
                request.DeliveryMode = (int)GlobalEnumVars.WeChatShippingDeliveryMode.UNIFIED_DELIVERY;
            }



            //构建请求
            var client = _weChatApiHttpClientFactory.CreateWxOpenClient();

            request.AccessToken = WeChatCacheAccessTokenHelper.GetWxOpenAccessToken();

            var response = await client.ExecuteWxaSecOrderUploadShippingInfoAsync(request, HttpContext.RequestAborted);

            if (response.IsSuccessful())
            {
                jm.code = 0;
                jm.data = new
                {
                    response
                };
                jm.msg = "提交成功";
            }
            else
            {
                jm.code = 1;
                jm.msg = response.ErrorMessage;
            }

            return jm;
        }
        #endregion

        #region 重新发货============================================================
        /// <summary>
        /// 重新发货
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("创建数据")]
        public async Task<AdminUiCallBack> GetUpdate([FromBody] FMStringId entity)
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };

            var paymentOrder = await _billPaymentsServices.QueryByClauseAsync(p => p.paymentId == entity.id);
            if (paymentOrder == null)
            {
                jm.msg = "支付单获取失败";
                return jm;
            }

            var status = EnumHelper.EnumToList<GlobalEnumVars.WeChatShippingOrderStatus>();
            var logisticsType = EnumHelper.EnumToList<GlobalEnumVars.WeChatShippingLogisticsType>();


            //构建请求
            var client = _weChatApiHttpClientFactory.CreateWxOpenClient();
            var accessToken = WeChatCacheAccessTokenHelper.GetWxOpenAccessToken();
            var request = new WxaSecOrderGetOrderRequest
            {
                AccessToken = accessToken,
                TransactionId = entity.data.ToString(),
                OutTradeNumber = entity.id
            };

            var deliveryCompany = await _weChatShippingDeliveryServices.GetCaChe();


            var response = await client.ExecuteWxaSecOrderGetOrderAsync(request, HttpContext.RequestAborted);
            if (response.IsSuccessful())
            {
                jm.code = 0;
                jm.data = new
                {
                    response.Order,
                    status,
                    logisticsType,
                    deliveryCompany
                };
            }
            else
            {
                jm.code = 1;
                jm.msg = response.ErrorMessage;
            }
            return jm;
        }
        #endregion

        #region 重新发货提交============================================================
        /// <summary>
        /// 重新发货提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("创建提交")]
        public AdminUiCallBack DoUpdate([FromBody] Object entity)
        {
            var jm = new AdminUiCallBack();

            return jm;
        }
        #endregion

        #region 预览数据============================================================
        // POST: Api/CoreCmsAgent/GetDetails/10
        /// <summary>
        /// 预览数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("预览数据")]
        public async Task<AdminUiCallBack> GetDetails([FromBody] FMStringId entity)
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };

            var paymentOrder = await _billPaymentsServices.QueryByClauseAsync(p => p.paymentId == entity.id);
            if (paymentOrder == null)
            {
                jm.msg = "支付单获取失败";
                return jm;
            }

            var orderTitle = string.Empty;

            if (paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.Recharge)
            {
                orderTitle = "用户充值" + paymentOrder.money + "元";
            }
            else if (paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.FormOrder)
            {
                orderTitle = "表单订单";
            }
            else if (paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.FormPay)
            {
                orderTitle = "表单付款码支付";
            }
            else if (paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.ServiceOrder)
            {
                var id = Convert.ToInt32(paymentOrder.sourceId);
                var serviceModel = await _servicesServices.QueryByClauseAsync(p => p.id == id);
                if (serviceModel == null)
                {
                    jm.msg = "服务项目获取失败";
                    return jm;
                }

                orderTitle = serviceModel.title;
            }
            else if (paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.Common
                        || paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.PinTuan
                        || paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.Group
                        || paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.Seckill
                        || paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.Solitaire
                     )
            {
                var orderItems = await _orderItemServices.QueryListByClauseAsync(p => p.orderId == paymentOrder.sourceId);
                if (!orderItems.Any())
                {
                    jm.msg = "订单详情获取失败";
                    return jm;
                }
                else
                {
                    if (orderItems.Count == 1)
                    {
                        orderTitle = orderItems.FirstOrDefault()?.name;
                    }
                    else
                    {
                        orderItems.ForEach(p => { orderTitle += p.name + ";"; });
                    }
                }
            }
            else if (paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.Bargain)
            {
                orderTitle = "砍价活动";
            }
            else if (paymentOrder.type == (int)GlobalEnumVars.BillPaymentsType.Giveaway)
            {
                orderTitle = "购物赠品";
            }
            else
            {
                jm.msg = "订单类型获取失败";
                return jm;
            }

            var status = EnumHelper.EnumToList<GlobalEnumVars.WeChatShippingOrderStatus>();
            var logisticsType = EnumHelper.EnumToList<GlobalEnumVars.WeChatShippingLogisticsType>();


            //构建请求
            var client = _weChatApiHttpClientFactory.CreateWxOpenClient();
            var accessToken = WeChatCacheAccessTokenHelper.GetWxOpenAccessToken();
            var request = new WxaSecOrderGetOrderRequest
            {
                AccessToken = accessToken,
                TransactionId = entity.data.ToString(),
                OutTradeNumber = entity.id
            };

            var deliveryCompany = await _weChatShippingDeliveryServices.GetCaChe();


            var response = await client.ExecuteWxaSecOrderGetOrderAsync(request, HttpContext.RequestAborted);
            if (response.IsSuccessful())
            {
                jm.code = 0;
                jm.data = new
                {
                    response.Order,
                    status,
                    logisticsType,
                    orderTitle,
                    deliveryCompany
                };
            }
            else
            {
                jm.code = 1;
                jm.msg = response.ErrorMessage;
            }
            return jm;
        }
        #endregion

    }
}
